package cn.myframe.service.sys.impl;

import cn.myframe.dao.sys.SysUserDao;
import cn.myframe.dao.sys.SysUserRoleDao;
import cn.myframe.entity.sys.SysUserEntity;
import cn.myframe.entity.sys.SysUserRoleEntity;
import cn.myframe.service.BaseServiceImpl;
import cn.myframe.service.sys.SysUserRoleService;
import cn.myframe.service.sys.SysUserService;
import cn.myframe.shiro.ShiroUtils;
import cn.myframe.utils.CryptPwdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@Service("sysUserService")
public class SysUserServiceImpl  extends BaseServiceImpl<SysUserDao,SysUserEntity> implements SysUserService {

	@Autowired
	private SysUserDao sysUserDao;
	@Autowired
	private SysUserRoleDao sysUserRoleDao;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	
    @Override
    public SysUserEntity queryByName(String name) {
        SysUserEntity sysUser = new SysUserEntity();
        sysUser.setUsername(name);
        return this.baseMapper.selectOne(sysUser);
    }

    @Override
	@Transactional(rollbackFor = Exception.class)
	public void save(SysUserEntity user) {
		user.setSalt(UUID.randomUUID().toString().replace("-", ""));
		user.setPassword(CryptPwdUtil.hmacSha256(user.getSalt()+ user.getUsername(),user.getPassword()));
		user.setConfirmPassword(CryptPwdUtil.hmacSha256(user.getSalt()+ user.getUsername(),user.getPassword()));
		user.setStatus(8);
		user.setCreateBy(ShiroUtils.getUserEntity().getUserId());
		user.setCreateTime(new Date());
		user.setLanguage("zh-CN");
		user.setType(2);
		sysUserDao.insert(user);

		insertUserRole(user);
	}

	private void insertUserRole(SysUserEntity user) {
		for (Long roleId : user.getRoleIdList()) {
			SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
			sysUserRoleEntity.setRoleId(roleId);
			sysUserRoleEntity.setUserId(user.getUserId());
			sysUserRoleDao.insert(sysUserRoleEntity);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(cacheNames = "userAllPermsCache", key = "'user:perms:' + #user.userId")
	public void update(SysUserEntity user) {
		user.setPassword(CryptPwdUtil.hmacSha256(user.getSalt()+ user.getUsername(),user.getPassword()));
		user.setConfirmPassword(CryptPwdUtil.hmacSha256(user.getSalt()+ user.getUsername(),user.getPassword()));
		user.setStatus(8);
		sysUserDao.updateById(user);
		sysUserRoleDao.deleteByUserIds(new Long[]{user.getUserId()});

		insertUserRole(user);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteByIds(Long[] ids) {
		for (Long id : ids) {
			sysUserDao.deleteById(id);
			sysUserRoleDao.deleteByUserIds(new Long[]{id});
		}
	}

	@Override
	public List<Long> selectIdsByCompanyIds(Collection<Long> relCompanyIds) {
		return baseMapper.selectIdsByCompanyIds(relCompanyIds);
	}

	@Override
	public int checkRepeat(String username, String userId) {
		return baseMapper.checkExist(userId, username, "USER_NAME");
	}

	@Override
	@Cacheable(cacheNames = "userAllPermsCache", key = "'user:perms:' + #userId")
	public List<String> queryAllPerms(Long userId) {
		return sysUserDao.queryAllPerms(userId);
	}

	@Override
	public List<Long> queryAllMenuId(Long userId) {
		return sysUserDao.queryAllMenuId(userId);
	}

	@Override
	public int updatePassword(Long userId, String password, String newPassword) {
		SysUserEntity user = sysUserDao.queryObject(userId);
		if(!CryptPwdUtil.hmacSha256(user.getSalt()+ user.getUsername(),password).equals(user.getPassword())){
			return 0;
		}
		password=user.getPassword();
		newPassword=CryptPwdUtil.hmacSha256(user.getSalt()+ user.getUsername(),newPassword);
		Map<String, Object> map = new HashMap<>();
		map.put("userId", userId);
		map.put("password", password);
		map.put("newPassword", newPassword);
		return sysUserDao.updatePassword(map);
	}

	@Override
	public List<Long> queryDataUser(Long userId, String perms, Long companyNo) {
		return sysUserDao.queryDataUser(userId, perms, companyNo);
	}

	@Override
	public List<Long> queryUserBySonCompany(Long companyNo) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Long> queryUserByCompanyNo(Long companyNo) {
		return sysUserDao.queryUserByCompanyNo(companyNo);
	}
	
	@Override
	public int updateLanguage(Long userId,String language) {
		// TODO Auto-generated method stub
		Map<String, Object> map = new HashMap<>();
		map.put("userId", userId);
		map.put("language", language);
		return sysUserDao.update(map);
	}
}
